<template>
  <view id="x-fixed" :class="classNameList">
    <view id="x-fixed-content" class="_content" :style="[styles]">
      <slot />
    </view>
  </view>
</template>

<script>
export default {
  name: 'XFixed',
  components: {},
  props: {
    background: {
      type: String,
      default: '#ffffff'
    },
    interval: {
      type: Number,
      default: 0
    },
    direction: {
      type: String,
      default: 'top' // bottom 底，top 顶
    },
    fixed: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isFixed: false,
      height: 0,
      retryCount: 0
    };
  },
  computed: {
    classNameList() {
      const name = ['x-fixed'];
      // 固定
      if (this.isFixed) {
        name.push('is-fixed');
      }
      return name.join(' ');
    },
    // 距离顶部位置
    fixedTop() {
      return this.interval;
    },
    styles() {
      return {
        [this.direction]: this.fixedTop + 'rpx',
        'background': this.background
      };
    }
  },
  watch: {},
  created() {
    this.isFixed = this.fixed;
    this.retryCount = 0;
  },
  mounted() {
    this.setHeight();
  },
  methods: {
    // 获取navigation信息
    setHeight() {
      const query = uni.createSelectorQuery().in(this);
      query.select('#x-fixed-content').boundingClientRect(data => {
        if (data) {
          this.height = data.height;
        } else {
          // 获取不到时，重试三次
          if (this.retryCount < 3) {
            setTimeout(() => {
              this.retryCount++;
              this.setHeight();
            }, 600);
          }
        }
      }).exec();
    },
    scrollTab() {
      const view = uni.createSelectorQuery().in(this);
      view.select('#x-fixed').boundingClientRect(res => {
        // 是否为固定悬浮状态
        // console.log(res.top, this.fixedTop)
        this.isFixed = res.top <= this.fixedTop;
      }).exec();
    }
  }
};
</script>

<style lang="scss">
.x-fixed{
  ._placeholder{ display: block;}
  ._content{ position: fixed; width: 100%; left: 0; z-index: 120;}
}
</style>
